package com.wzdigit.wms.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;


/**
 * 处理前端传递参数中带有""的空字段工具
 * @author yshh276
 */
public class NullParamsUtils {
    public static <T> void transfernull(Class<T> classes, Object obj) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //通过类类型，获取此类型中的字段
        Field[] fields = classes.getDeclaredFields();
        //遍历所有字段
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(obj);
            Method method;
            if (StringUtils.isBlank(String.valueOf(value)) || value == null) {
                method = classes.getDeclaredMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), field.getType());
                method.invoke(obj, new Object[]{null});
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static void transfer(Map map){
        Set set = map.keySet();
        for(Object key:set){
            if(StringUtils.isBlank(String.valueOf(map.get(key)))|| map.get(key)==null){
                map.put(key,null);
            }
        }
        //return map;
    }

    /** 去掉所有搜索条件字段空格 */
    public static <T> void transferSearchNull(Class<T> classes, Object obj) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //通过类类型，获取此类型中的字段
        Field[] fields = classes.getDeclaredFields();
        //遍历所有字段
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(obj);
            Method method;
            if (StringUtils.isNotBlank(String.valueOf(value)) && value != null && !"serialVersionUID".equalsIgnoreCase(name)) {
                method = classes.getDeclaredMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), field.getType());
                method.invoke(obj, new Object[]{String.valueOf(value).replace(" ","")});
            }
        }
    }

}
